<template>
    <div>
        <el-upload
            :action="QINIUUPLOADURL"
            :multiple="false"
            ref="upload"
            list-type="picture-card"
            :limit="1"
            :data="qiniuData"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemovePic"
            :on-error="handleError"
            :before-upload="beforeAvatarUpload"
            :on-preview="$imgPreview"
            :file-list="qiniuData.fileList" 
            >
            <i class="el-icon-plus"></i>
        </el-upload>
         <el-button type="primary" @click="quitUp()" style="margin: 15px 0;">确认提交</el-button>
    </div>
</template>
<script>

import util from '@/utils/util'
import { qnToken } from '@/api/api'

export default {
  name:'UpLoadLayer',
  data () {
    return {
      msg: '上传分层图',
      //上传图片携带的参数
      qiniuData:{
        token : "",
        key : "",
        fileList:[],
      },
  	}
  },
  props:{
    callBackUrl:{
      type: Function,
      required: true
    }
  },
  created(){
    this.getToken();
  },
  methods:{
      getToken(){  //上传之前获取 token
        qnToken({}).then((result) => {
          this.qiniuData.token= result.data
        })
      },
      handleAvatarSuccess: function(res, file, fileList) {//上传成功
        this.qiniuData.fileList = fileList;
      },
      handleRemovePic: function(file, fileList) {//删除成功
        this.qiniuData.fileList = fileList;
      },
      handleError: function(res) {
        this.$message({
          message: "上传失败",
          duration: 2000,
          type: "warning"
        });
      },
      beforeAvatarUpload: function(file){//重命名和校验
        var fielLocal = file.name.split(".")
        var fielType = "." + fielLocal[fielLocal.length-1]
        var fielLocalName = fielLocal[0]
        this.qiniuData.key = 'ilink_'+new Date().getTime()+fielType   
        const isJPG = file.type === "image/jpeg";
        const isPNG = file.type === "image/png";
        const isLt20M = file.size / 1024 / 1024 < 20;
        if (!isJPG && !isPNG) {
          this.$message.error("图片只能是 JPG/PNG 格式!");
          return false;
        }
        if (!isLt20M) {
          this.$message.error("图片大小不能超过 20MB!");
          return false;
        }
      },
      quitUp(){
        let url = util.ilinkArrHandle.getqiniuPicUrlArr(this.qiniuData.fileList).toString();
        this.callBackUrl(url);
        this.qiniuData.fileList = [];
      }
  }
}
</script>

<style lang="less">
</style>
